<template>
  <a-modal :visible="visible" title="批量分配流程权限" @ok="handleOk" @cancel="handleCancel" @update:visible="handleVisible">
    <a-form :model="form" :label-col="{ span: 6 }" :wrapper-col="{ span: 16 }">
      <a-form-item label="角色" name="roleId" required>
        <a-select v-model:value="form.roleId" placeholder="请选择角色" :options="roleOptions" />
      </a-form-item>
      <a-form-item label="流程" name="processKeys" required>
        <a-select v-model:value="form.processKeys" mode="multiple" placeholder="请选择流程" :options="processOptions" @change="val => console.log('选中流程:', val)" />
      </a-form-item>
    </a-form>
  </a-modal>
</template>

<script setup lang="ts">
import { ref, watch, onMounted, reactive } from 'vue';
import { batchAssignRoleProcessPerm } from '@/api/workflow/roleProcessPerm.api';
import { listRoleApi } from '@/api/system/authority/role.api';
import { getProcessList } from '@/api/workflow/process.api';
import { message } from 'ant-design-vue';
import { ElMessage } from 'element-plus'
import Icon from '@/components/Icon/Icon.vue'

// 引入统一的夜间模式样式
import '@/components/Workflow/styles/dark-theme.css'

// 明确类型，保证processKeys为string[]
/**
 * @typedef {Object} FormState
 * @property {string|number} roleId
 * @property {string[]} processKeys
 */

const props = defineProps({ visible: Boolean });
const emit = defineEmits(['update:visible', 'ok']);

/** @type {import('vue').Ref<FormState>} */
const form = reactive({ roleId: '', processKeys: [] });
const roleOptions = ref([]);
const processOptions = ref([]);

watch(
  () => props.visible,
  (val) => {
    if (val) {
      form.roleId = '';
      form.processKeys = [];
    }
  },
  { immediate: true }
);

async function fetchRoles() {
  const res = await listRoleApi();
  roleOptions.value = (res?.items || res?.rows || []).map((r) => ({ label: r.name, value: r.id }));
}

async function fetchProcesses() {
  const res = await getProcessList({});
  // 兼容不同返回结构
  const items = res?.data?.items || res?.items || res?.rows || [];
  processOptions.value = items.map((p) => ({ label: p.name, value: p.processKey }));
}

onMounted(() => {
  fetchRoles();
  fetchProcesses();
});

function handleOk() {
  if (!form.roleId || !form.processKeys.length) {
    message.warning('请选择角色和流程');
    return;
  }
  batchAssignRoleProcessPerm({ roleId: form.roleId, processKeys: form.processKeys }).then(() => {
    message.success('批量分配成功');
    emit('update:visible', false);
    emit('ok');
  });
}
function handleCancel() {
  emit('update:visible', false);
}
function handleVisible(val) {
  emit('update:visible', val);
}
</script> 